package cn.edu.neu.softlab.jason.offer.jianzhioffer.datastructure.util;

public class LinkedList {
    public static LinkedNode addToTail(LinkedNode head, LinkedNode node) {
        LinkedNode tail = findTail(head);
        if (tail == null) {
            head = node;
        } else {
            tail.next = node;
        }
        return head;
    }

    public static LinkedNode addToTail(LinkedNode head, int value) {
        LinkedNode node = new LinkedNode(value);
        return addToTail(head, node);
    }

    public static LinkedNode removeNode(LinkedNode head, int value) {
        if (head == null) {
            return head;
        }

        LinkedNode node = head;
        if (head.value == value) {
            head = head.next;
        } else {
            while (node.next != null && node.next.value != value) {
                node = node.next;
            }
            if (node.next != null && node.next.value == value) {
                node.next = node.next.next;
            } else {
                System.out.println("链表中没有" + value);
            }
        }

        return head;
    }

    private static LinkedNode findTail(LinkedNode head) {
        if (head == null) {
            return null;
        }
        LinkedNode node = head;
        while (node.next != null) {
            node = node.next;
        }
        return node;
    }
}
